package com.mvpandroiddemo.login;


import com.mvpandroiddemo.net.APIHelper;
import com.mvpandroiddemo.register.RegisterBean;
import com.mvpandroiddemo.utils.Constance;
import com.mvpandroiddemo.utils.SharedPreferenceHelper;
import com.orhanobut.logger.Logger;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

//数据源
public class LoginModel implements LoginControl.ILoginModel {

    private LoginPresent loginPresent;
    private SharedPreferenceHelper instance = SharedPreferenceHelper.getInstance();

    public LoginModel(LoginPresent loginPresent) {
        this.loginPresent = loginPresent;
    }


    @Override
    public String initModelUserName() {
        String userName = instance.getString(Constance.Cache_user_name);
        Logger.i("从缓存中读取名称 => " + userName);

        return userName;
    }

    @Override
    public String initModelPwd() {
        String pwd = instance.getString(Constance.Cache_user_pwd);
        Logger.i("从缓存中获取密码 => " + pwd);
        return pwd;
    }

    @Override
    public void login(String userName, String pwd) {
        Disposable disposable = APIHelper.getInstance()
                .getNetServices()
                .login(userName, pwd)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(baseBean -> {
                    Logger.i("登录成功 => " + baseBean.toString());
                    int errorCode = baseBean.getErrorCode();
                    if (errorCode == Constance.Net_Tag_failure) {
                        loginPresent.loginFailure(baseBean.getErrorMsg());
                    } else {
                        SharedPreferenceHelper preferenceHelper = SharedPreferenceHelper.getInstance();
                        preferenceHelper.saveData(Constance.Cache_user_name, userName);
                        preferenceHelper.saveData(Constance.Cache_user_pwd, pwd);
                        APIHelper.getInstance().init();
                        loginPresent.loginSuccess();
                    }
                }, throwable -> {

                    loginPresent.loginFailure(throwable.getMessage());
                });
    }
}
